var util = require('../../utils/util.js')
const db = wx.cloud.database()
//获取应用实例
var app = getApp()

Page({
  data: {
    goodsList: [],
    isNeedLogistics: 0, // 是否需要物流信息(收货地址)
    allGoodsPrice: 0,
    yunPrice: 0,
    allGoodsAndYunPrice: 0,
    goodsJsonStr: "",
    orderType: "", //订单类型，购物车下单或立即支付下单，默认是购物车，
    curAddressData:null,
    hasNoCoupons: true,
    coupons: [],
    youhuijine: 0, //优惠券金额
    curCoupon: null, // 当前选择使用的优惠券
    tijaoStatus:false
  },
  onShow: function () {
    
    var that = this;
    that.setData({
      tijaoStatus: false
    })
    var shopList = [];
    //立即购买下单
    if ("buyNow" === that.data.orderType) {
      console.log('立即下单!!')
      var buyNowInfoMem = wx.getStorageSync('buyNowInfo');
      that.data.kjId = buyNowInfoMem.kjId;
      if (buyNowInfoMem && buyNowInfoMem.shopList) {
        shopList = buyNowInfoMem.shopList
      }
    } else {
      //购物车下单
      var shopCarInfoMem = wx.getStorageSync('shopCarInfo');
      that.data.kjId = shopCarInfoMem.kjId;
      if (shopCarInfoMem && shopCarInfoMem.shopList) {
         shopList = shopCarInfoMem.shopList
        shopList = shopCarInfoMem.shopList.filter(entity => {
          return entity.active;
        });
      }
    }
    that.setData({
      goodsList: shopList,
    });
    //加载就显示地址
    that.initShippingAddress();
  },

  onLoad: function (e) {
    
    var that = this;
    console.log(e)
    //显示收货地址标识
    if(e.orderType){
      that.setData({
        orderType: e.orderType
      });
    }
    that.setData({
      isNeedLogistics: 1,
      orderType: e.orderType
    });
  },

  getDistrictId: function (obj, aaa) {
    if (!obj) {
      return "";
    }
    if (!aaa) {
      return "";
    }
    return aaa;
  },
  //创建order
  readyOrder: function (e) {
    
    var that = this;
   // wx.showLoading();
    var loginToken = wx.getStorageSync('token') // 用户登录 token
    var remark = ""; // 备注信息
     //优惠券
     that.getMyCoupons();
    if (e) {
      remark = e.detail.value.remark; // 备注信息
    }

    var postData = {
      token: loginToken,
      goodsJsonStr: that.data.goodsJsonStr,
      remark: remark
    };
    if (that.data.kjId) {
      postData.kjid = that.data.kjId;
    }
    if (that.data.isNeedLogistics > 0) {
      console.log(that.data.curAddressData)
      if (!that.data.curAddressData) {
        wx.hideLoading();
        wx.showModal({
          title: '错误',
          content: '请先设置您的收货地址！',
          showCancel: false
        })
        return;
      }
    
      
    }
  
  

  },
  initShippingAddress: function () {
    var that = this;
    
      //查询云数据库
    
      const b = db.collection('useraddress').where({
        _openid: wx.getStorageSync('openid')
      }).orderBy("dateAdd","desc").get({
        success: function(res) {
        console.log(res)
        //  请求当前地址数据
        if (res.data.length> 0 ) {
          that.setData({
            curAddressData: res.data[0]//只是查最新地址
          });
          if( !res.data[0].mobile){
            wx.showModal({
              title: '错误',
              content: '请先设置您的收货信息！',
              showCancel: false
            })
          }else{
            //计算运费总费用
            that.processYunfei();
          }
          
        } else {
          that.setData({
            curAddressData: null
          });
          wx.hideLoading();
          wx.showModal({
            title: '错误',
            content: '请先设置您的收货信息！',
            showCancel: false
          })
        }
       }
     })

  
    
      
      
  },
  processYunfei: function () {
    
    var that = this;
    var goodsList = this.data.goodsList;
    var goodsJsonStr = "[";
   // var isNeedLogistics = 0;
    var allGoodsPrice = 0;

    for (let i = 0; i < goodsList.length; i++) {
      let carShopBean = goodsList[i];
      //if (carShopBean.logistics) {
      //  isNeedLogistics = 1;
     // }
      allGoodsPrice += carShopBean.price * carShopBean.number;

      var goodsJsonStrTmp = '';
      if (i > 0) {
        goodsJsonStrTmp = ",";
      }
      goodsJsonStrTmp += '{"goodsId":' + carShopBean.goodsId + ',"number":' + carShopBean.number + ',"propertyChildIds":"' + carShopBean.propertyChildIds + '","logisticsType":0}';
      goodsJsonStr += goodsJsonStrTmp;


    }
    goodsJsonStr += "]";
    that.setData({
     // isNeedLogistics: isNeedLogistics,
      goodsJsonStr: goodsJsonStr,
      //
      allGoodsAndYunPrice:allGoodsPrice
    });
    that.readyOrder();
  },
  addAddress: function () {
    wx.navigateTo({
      url: "/pages/address-add/index"
    })
  },
  selectAddress: function () {
    wx.navigateTo({
      url: "/pages/select-address/index"
    })
  },
  getMyCoupons: function () {
    var that = this;
    const _ =db.command
    db.collection('coupons').where({
      _openid: wx.getStorageSync('openid'),
      moneyHreshold:_.lt(that.data.allGoodsAndYunPrice),
      money:_.lt(that.data.allGoodsAndYunPrice),
      status:0,
      dateEnd:_.gt(new Date())
    }).orderBy("money","desc").get({
      success: function(res) {
        console.log(res)
        
          if (res.data.length > 0) {
            that.setData({
              hasNoCoupons: false,
              coupons: res.data
            });
          }
        //}
      }
    })
  },
  //选择优惠券
  bindChangeCoupon: function (e) {
    
    const selIndex = e.detail.value[0] - 1;
    if (selIndex === -1) {
      this.setData({
        youhuijine: 0,
        curCoupon: null
      });
      wx.removeStorageSync('curCoupon')
      return;
    }
    
    //console.log("selIndex:" + selIndex);
    this.setData({
      youhuijine: this.data.coupons[selIndex].money,
      curCoupon: this.data.coupons[selIndex]
    });
    wx.setStorageSync('curCoupon', this.data.coupons[selIndex])
  },

   // 提交支付
  createOrder(e){
    let that = this;
    if(!that.data.curAddressData  || !that.data.curAddressData.mobile){
      wx.showModal({
        title: '错误',
        content: '请先补全您的收货信息！',
        showCancel: false
      })
      return
  }
    wx.showLoading();
    
    that.setData({
      tijaoStatus:true
    })
    const  db = wx.cloud.database()
   
    var timeStamp ="1999"+ Date.parse(new Date()) / 1000;// new Date().getTime()//orderid
    var couponamont = ""  
    if(that.data.curCoupon){
      couponamont = that.data.curCoupon.money
    }
  //that.data.curAddressData.provinceStr+that.data.curAddressData.cityStr+that.data.curAddressData.districStr+
    db.collection('orders').add({
      data: {
        amount:that.data.allGoodsAndYunPrice,//商品金额
        amountLogistics:0,//运费
        amountReal:that.data.allGoodsAndYunPrice-that.data.youhuijine,
        dateAdd: util.formatTime( new Date()),
        is_send:"",//是否发送
        logistics: {
          address:that.data.curAddressData.address,
          linkMan:that.data.curAddressData.linkMan,
          mobile:that.data.curAddressData.mobile,
         // provinceStr:that.data.curAddressData.provinceStr,
         // provinceId:that.data.curAddressData.provinceId,
         // districtId:that.data.curAddressData.districtId,
         // districStr:that.data.curAddressData.districStr,
         // cityId:that.data.curAddressData.cityId,
         // cityStr:that.data.curAddressData.cityStr,
          trackingNumber:"", // 快递单号
        
        },
       // logisticsStatus:0,//货物状态0
        logisticsTraces:"",  //物流跟踪
        remark:e.detail.value.remark,
        score:0,  //积分
        status:0,
        goods:this.data.goodsList,
        orderNumber:timeStamp,  //订单编号
        couponamont:couponamont ,//优惠券id
        delivered:0,//是否已送货 0未送
        deliveredMan:"",
        hasRefund:0//配送人
      },
      success: function(res) {
        if (!res._id ) {
              wx.showModal({
                title: '错误',
                content: "fail",
                showCancel: false
              })
              return;
        }
           
        //修改已使用的优惠券状态
        let couponed =  wx.getStorageSync('curCoupon');
        if(couponed){
          const db = wx.cloud.database()
          db.collection('coupons').doc(couponed._id).update({
            data: {
            status:1
            },
            success: function(res) {
              console.log(res)
              wx.removeStorageSync('curCoupon');
              
            }
          })
        }
        if (e && "buyNow" != that.data.orderType) {
            // 清空购物车数据
            let cargoods =  wx.getStorageSync('shopCarInfo').shopList;
            var shopCar = {
              shopNum:0,
              shopList:[]
            }
          
            var num = 0
            for (let index = 0; index < cargoods.length; index++) {
              const good = cargoods[index];
              if(!good.active ){
              shopCar.shopList.push(good)
              shopCar.shopNum++;
              }else{
                //减库存
                that.updateStores(good)
              }
            }
            wx.removeStorageSync('shopCarInfo');
            wx.setStorageSync('shopCarInfo',shopCar);
        }else{
          
          //商品详情页直接下单
          let buyNowInfogoods =  wx.getStorageSync('buyNowInfo').shopList;

          for (let index = 0; index < buyNowInfogoods.length; index++) {
            const buyNow = buyNowInfogoods[index];
            if(buyNow.active ){
               //减库存
               that.updateStores(buyNow)
            }
          }
          //删除Storage的数据
          wx.removeStorageSync('buyNowInfo');
        }
        //支付
        wx.hideLoading();
            wx.cloud.callFunction({
              name: "payFun",
              data: {
                body: "超市",
                orderid: timeStamp,
                money:1,
                nonceStr:"455"
              },
              success(res) {
                console.log("scucess", res)
                wx.hideLoading({
                  complete: (res) => {},
                })
                console.log("提交成功", res.result)
                //创建订单操作，在自定义的保存订单的成功回调中使用下面的函数
                //this.pay(res.result, res._id)
                const payment = res.result.payment
                wx.requestPayment({
                  ...payment, //。。。是展开变量的语法 
                  success(res) {
                    console.log("pay success", res)
                    //跳转到支付成功页面
                    wx.redirectTo({
                      url: "../order/index?type=0"
                    });
                  },
                  fail(res) {
                    console.error("pay fail", res)
                    //跳转到支付失败页面
                    // 跳转到订单管理界面
                    wx.showModal({
                      title: '错误',
                      content: '支付功能未开通',
                      showCancel: false
                    })
                    wx.redirectTo({
                      url: "../order/index?type=0"
                    });
                  }
                })
              },
              fail(res) {
                  wx.hideLoading({
                    complete: (res) => {},
                  })
                  console.log("提交失败", res)
                  wx.redirectTo({
                    url: "../order/index"
                  });
                }
              })
          }
      })
  },
  updateStores(good){
    
    let upnum  = good.number
    const _ = db.command
	//库存减1 inc(-1)
    db.collection('goods').doc(good.goodsId).update({
      data: {
        stores: _.inc(-upnum),
        numberOrders: _.inc(upnum),
      }, success: function(res) {
      
      console.log(res)
      
      },fail:function(res) {
        console.log("提交失败", res)
        wx.redirectTo({
          url: "../order/index"
        });
      }
    }) 
  },

})
